const sass = require("sass");
const fs = require("fs-extra");
const chalk = require("chalk");
const config = require("./theme.config.json");

const THEME_ENUM = config.themes.map((theme) => theme.color.toLocaleLowerCase());

console.log("Theme loding ...");

THEME_ENUM.forEach((color) => {
  const scssContent = `
    $--color-primary: ${color};
    @import "../../node_modules/element-ui/packages/theme-chalk/src/index";
  `;
  const scssPath = `./src/theme/tmp.${color.replace("#", "")}.scss`;

  // 生成临时文件
  fs.ensureFileSync(scssPath);
  fs.writeFileSync(scssPath, scssContent);

  const cssPath = `./public/theme/style.${color.replace("#", "")}.css`;

  sass.render(
    {
      file: scssPath,
      outFile: cssPath,
      sourceMap: true,
    },
    function (err, result) {
      // 移除自定义字体部分代码
      const cssContent = result.css
        .toString()
        .replace(/@font-face\s?{[^}]*}/, "");
      fs.ensureFileSync(cssPath);
      fs.writeFileSync(cssPath, cssContent);

      // 移除临时文件
      fs.remove(scssPath);

      const message = [
        chalk.green(scssPath),
        chalk.yellow("->"),
        chalk.green(cssPath),
      ];

      console.log(...message);
    }
  );
});
